# -*- coding: utf-8 -*-
import numpy as np
import base64
from hashlib import md5
from FooderUtil.feaextract import getFeaFromlargeBaseImg
from FooderUtil.serialization_tool import dictSerializToStr

class FooderSearchError(RuntimeError):
    def __init__(self, errMsg):
        self.errMsg = errMsg

    def data(self, errDetails):
        self.errDetails = errDetails
        return self

ErrSearchReqParam = FooderSearchError("缺少必选的请求参数")

class FoodSearch(object):
    def __init__(self):
        pass

    def search(self, j_data, context, shopId, foodRedis, foodTable, foodOss):
        if 'image' not in j_data.keys() or \
           'targetData' not in j_data.keys():
            raise ErrSearchReqParam.data(f'缺少image or targetData')
        base64_large_img = j_data['image']
        targetData = j_data['targetData']
        bboxex = []
        for box in targetData:
            bbox = [box['left'], box['top'], box['right'], box['bottom']]
            bboxex.append(bbox)
        # bboxes = [[743, 234, 1213, 740], [322, 193, 639, 505]]
        feats = getFeaFromlargeBaseImg(base64_large_img, bboxex)
        ids_results, scores_result, repo_count = foodRedis.feas_search(shopId, feats)
        # 处理识别结果
        resultNum = len(bboxex)
        resultList = []
        for i in range(resultNum):
            resultN = {
                'location': {
                    'left': bboxex[i][0],
                    'top': bboxex[i][1],
                    'right': bboxex[i][2],
                    'bottom': bboxex[i][3]
                },
                'dishes': []
            }
            idList, scoreList = [], []
            for j in range(repo_count):
                k = j + i * repo_count
                idList.append(ids_results[k])
                scoreList.append(scores_result[k])
        
            # 筛选dishId与feaId、score对应关系
            dishId_feaId_score = {}
            for m in range(len(idList)):
                dishId_feaId = idList[m]
                dishId_feaIds = dishId_feaId.split(':')
                dishId = dishId_feaIds[0]
                feaId = dishId_feaIds[1]
                if dishId not in dishId_feaId_score:
                    dishId_feaId_score[dishId] = [feaId, scoreList[m]]

            # 获取菜品的其它信息
            # print(dishId_feaId_score)
            dishes = []
            for dishId in dishId_feaId_score:
                feaId = dishId_feaId_score[dishId][0]
                score = dishId_feaId_score[dishId][1]
                primary_key = [('shopId', shopId), ('dishId', dishId)]
                dishName, dishPrice = foodTable.get_dishInfoByDishId(context, primary_key)
                topN = {
                    'dishId': dishId, 
                    'score': score, 
                    'dishName': dishName, 
                    'dishPrice': dishPrice,
                    'imageUrl': f'https://{foodOss.bucket_name}.oss-cn-beijing.aliyuncs.com/{shopId}/{feaId}.jpg'
                }
                dishes.append(topN)

            resultN['dishes']  = dishes
            resultList.append(resultN)
        return resultList, resultNum